package com.dongdong.realm;

import com.dongdong.token.LoginEnum;
import com.dongdong.api.AdminApi;
import com.dongdong.api.SellerApi;
import com.dongdong.model.TbAdmin;
import com.dongdong.model.TbSeller;
import com.dongdong.token.LoginToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private SellerApi sellerApi;
    @Autowired
    private AdminApi adminApi;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("登录");
        LoginToken token = (LoginToken) authenticationToken;


        SimpleAuthenticationInfo sim = null;
        if (Objects.equals(token.getLoginEnum(), LoginEnum.SELLER)){
            TbSeller seller = sellerApi.getSellerByName(token.getUsername());
            if (seller == null){
                return null;
            }
            sim = new SimpleAuthenticationInfo(seller,seller.getPassword(),ByteSource.Util.bytes(seller.getSalt()),"sellerRealm");
        }

        if (Objects.equals(token.getLoginEnum(), LoginEnum.ADMIN)){
            TbAdmin admin = adminApi.getAdminByName(token.getUsername());
            if (admin == null){
                return null;
            }
            sim = new SimpleAuthenticationInfo(admin,admin.getPwd(),ByteSource.Util.bytes(admin.getSalt()),"adminRealm");
        }


        return sim;
    }
}
